import  localForage  from 'localforage';
import { cloneDeep } from 'lodash-es';

export const persistStorage = localForage.createInstance({
    name: 'pinia-persist'
});

// 修改后的 persistPlugin
export const persistPlugin = ({ store }) => {
    // 增加返回 Promise 的水合逻辑
    store.$hydrate = () => {
        return new Promise((resolve, reject) => {
            persistStorage.getItem(store.$id)
                .then((savedState) => {
                    if (savedState) {
                        store.$patch(cloneDeep(savedState));
                    }
                    resolve(); // 数据加载完成
                })
                .catch((error) => {
                    console.error('水合失败:', error);
                    reject(error);
                });
        });
    };

    // 保留订阅逻辑
    store.$subscribe((mutation, state) => {
        const serializableState = cloneDeep(state);
        persistStorage.setItem(store.$id, serializableState);
    });
};